//
//  CTPSpotModel.m
//  citipad
//
//  Created by Chih Yuan Liu on 3/16/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CTPSpotModel.h"
#import "CTPSpot.h"
#import "constants.h"


@implementation CTPSpotModel

-(id)initWithCityName:(NSString*)cityName{
	if(self = [super init]){
		mydb = [FMDatabase databaseWithPath:[constants GetDBPath]];
		[self createDB];
		[self loadIntoArray:cityName];
		city = cityName;
		//array = [[NSArray alloc] initWithObjects:@"Shanghai", @"Taipei", @"Beijing", @"New York", nil];
	}
	return self;
}

-(void) loadIntoArray:(NSString*)cityName{
	if([mydb open]){
		array = [[NSMutableArray alloc]init];
		FMResultSet *rs = [mydb executeQuery:@"select * from spots where city= ? ", cityName];
		NSLog(@"%s , %@", __PRETTY_FUNCTION__, cityName);
		while ([rs next]) {
			[array addObject:[rs stringForColumn:@"name"]];
		}	
	}
}

-(void) createDB{
	if (![mydb open]) {
		NSLog(@"%s, Could not open db.", __PRETTY_FUNCTION__);
	}else {
		NSLog(@"%s, opened db", __PRETTY_FUNCTION__);
		[mydb executeUpdate:@"create table spots (name text, city text)", nil];
	}
}

-(void) removeSpot:(CTPSpot*)spot{
	mydb = [FMDatabase databaseWithPath:[constants GetDBPath]];
	NSUInteger index = [array indexOfObject:spot.name];
	if(index != NSNotFound){
		[array removeObjectAtIndex:index];
		if([mydb open]){
			[mydb beginTransaction];
			NSLog(@"%s, %@", __PRETTY_FUNCTION__, spot.name);
			[mydb executeUpdate:@"delete from spots where name =  ?" , spot.name];
			[mydb commit];
			[mydb close];
		}
	}
}

-(void) addSpot:(CTPSpot*)spot {
	mydb = [FMDatabase databaseWithPath:[constants GetDBPath]];
	NSLog(@"%s, %@", __PRETTY_FUNCTION__, spot.name);
	NSUInteger index = [array indexOfObject:spot.name];
	if(index == NSNotFound){
		if([mydb open]){
			[mydb beginTransaction];
			NSLog(@"%s %@", __PRETTY_FUNCTION__, spot.cityName);
			[mydb executeUpdate:@"insert into spots (name, city) values (?, ?)" , spot.name, spot.cityName];
			[mydb commit];
			[mydb close];
			[array addObject:spot.name];
		}
	}
}

-(NSInteger)GetCount{
	if(array==nil)
		return 0;
	return array.count;
}


-(CTPSpot*) GetItemAtIndex:(int)index{
	CTPSpot* spot = [[CTPSpot alloc] init];
	spot.name = [NSString stringWithFormat:@"%@", [array objectAtIndex:index]];
	spot.cityName = city;
	spot.imageKey = [NSString stringWithFormat:@"%@.png", [array objectAtIndex:index]];
	return spot;
}

@end
